package com.liukai.exam.service.impl;

import com.liukai.exam.pojo.SysUser;
import com.liukai.exam.mapper.SysUserMapper;
import com.liukai.exam.service.ISysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liukai.exam.utils.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author liu kai
 * @since 2021-02-01
 */
@Service
@Slf4j
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    private static final List ALLOW_IMAGE_TYPE = Arrays.asList("image/jpeg");

    @Value("${myFileLocation}")
    private String myFileLocation;

    @Override
    public SysUser login(SysUser sysUser) {
        return sysUserMapper.login(sysUser);
    }

    /**
     * 获取用户信息
     *
     * @param userId
     * @param classId
     * @return
     */
    @Override
    public SysUser getUserInfoById(Long userId, Integer classId) {
        return sysUserMapper.getUserInfoById(userId, classId);
    }

    /**
     * 修改用户信息
     *
     * @param sysUser
     * @return
     */
    @Override
    public int updateUserInfoById(SysUser sysUser) {
        return sysUserMapper.updateUserInfoById(sysUser);
    }

    /**
     * 修改用户头像
     *
     * @param userId
     * @param classId
     * @return
     */
    @Override
    public int updateHeadImgById(MultipartFile file, Long userId, Integer classId) {

        //判断图片类型
        String imageType = file.getContentType();
        if (!ALLOW_IMAGE_TYPE.contains(imageType)) {
            // 修改头像失败
            return -1;
        }
        //解析图片内容
        BufferedImage bufferedImage = null;
        try {
            bufferedImage = ImageIO.read(file.getInputStream());
        } catch (IOException e) {
            // 修改头像失败
            return -1;
        }
        if (bufferedImage == null) {
            // 修改头像失败
            return -1;
        }
        //设置上传图片名称
        long time = new Date().getTime();
        String imageName = time + ".jpg";
        File imagePathFile = new File(myFileLocation + "\\headImg");
        //上传图片
        try {
            file.transferTo(new File(imagePathFile, imageName));
        } catch (IOException e) {
            // 修改头像失败
            return -1;
        }
        String headUrl = imageName;
        log.info(headUrl);
        return sysUserMapper.updateHeadImgById(userId, classId, headUrl);
    }

    /**
     * 获取头像
     *
     * @param headImg 头像地址
     * @return
     */
    @Override
    public ResponseEntity<byte[]> getHeadImgByUrl(String headImg) throws Exception {

        byte[] imageContent;
        String path = myFileLocation + "\\headImg\\" + headImg;
        imageContent = fileToByte(new File(path));
        log.info("==================>" + path);
        final HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.IMAGE_PNG);
        return new ResponseEntity<>(imageContent, headers, HttpStatus.OK);

    }

    /**
     * 文件转换为字节流
     *
     * @param img
     * @return
     * @throws Exception
     */
    public static byte[] fileToByte(File img) throws Exception {
        byte[] bytes = null;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            BufferedImage bi;
            bi = ImageIO.read(img);
            ImageIO.write(bi, "png", baos);
            bytes = baos.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            baos.close();
        }
        return bytes;
    }

}
